package org.jeecg.modules.demo.oa.service.impl;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.TemplateMessageDTO;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.modules.demo.utils.MsgUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.oa.entity.ComApprovalList;
import org.jeecg.modules.demo.oa.entity.ComApprovalListLog;
import org.jeecg.modules.demo.oa.mapper.ComApprovalListMapper;
import org.jeecg.modules.demo.oa.service.IComApprovalListLogService;
import org.jeecg.modules.demo.oa.service.IComApprovalListService;
import org.jeecg.modules.demo.oa.vo.ShenPiData;
import org.jeecg.modules.message.util.PushMsgUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 审批清单
 * @Author: jeecg-boot
 * @Date:   2024-09-13
 * @Version: V1.0
 */
@Service
public class ComApprovalListServiceImpl extends ServiceImpl<ComApprovalListMapper, ComApprovalList> implements IComApprovalListService {
    @Autowired
    private IComApprovalListService comApprovalListService;
    @Autowired
    private IComApprovalListLogService comApprovalListLogService;

    @Autowired
    private PushMsgUtil pushMsgUtil;

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    /**
     * 审批
     * @param comApprovalList   审批清单表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void shenpi(ComApprovalList comApprovalList) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = sysUser.getUsername();
//       1. 获取要审批的表名
        String tableName = comApprovalList.getTableName();
        //2 获取要审批的主键
        String tableRecordId = comApprovalList.getTableRecordId();
        //3. 获取审批结果的列名
        String resultColName = comApprovalList.getResultColName();
        //4. 获取审批意见的列名
        String yijianColName = comApprovalList.getYijianColName();
        //5. 获取审批时间列名
        String timeColName = comApprovalList.getTimeColName();
        //6. 获取审批日志列名
        String shenpiLogColName = comApprovalList.getLogColName();

        //7. 获取审批状态列名
        String SignResult = comApprovalList.getSignResult();


        //8. 获取审批意见
        String yijian = comApprovalList.getSignYijian();

        //9. 获取主表主键列名
        String mainIdColName = comApprovalList.getMainIdColName();

        //9. 获取审批时间
        Date shenpiTime = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String shenpiTimeStr = sdf.format(shenpiTime);

        //10. 日志数据更新
        String shenpiLog = "";
        String strCishu="首次";
        if(resultColName.endsWith("2")){
            strCishu="二次";
        }
        shenpiLog = username+ " "+ strCishu + "审批 "+ shenpiTimeStr + " "+ SignResult + "("+ yijian+")";

        String billType = comApprovalList.getBillType();
        String billNo = comApprovalList.getBillNo();


        //主表名
        String mainTableName = tableName.replace("_shenpi", "");
        String mainRecordId = baseMapper.getMainRecordId(tableName, tableRecordId, mainIdColName);

        //得到申请用户名
        String shenqinBy = comApprovalList.getShenqinBy(); //baseMapper.getShenQinUserName(mainTableName, mainRecordId);
        String shenqinTimeStr  =  sdf.format(comApprovalList.getShenqinTime());  //baseMapper.getShenQinTime(mainTableName, mainRecordId);

        String shenpiBy = username ;// comApprovalList.getShenpiBy();

        String msgContent = billType+ ":\n 单据号："+ billNo
                + "\n 审批人："+ comApprovalList.getShenpiBy() + "\n 审批意见："+ yijian
                + "\n 审批结果："+ SignResult + "\n 审批时间："+ shenpiTimeStr;

      //  msgUtils.sendMesage(shenqinUserName, "您的"+ billType+"("+ billNo+")被审批"+ SignResult, msgContent,billNo);

        String billName = comApprovalList.getBillName();

        //给申请用户发送消息
        Map<String, String> map = new HashMap<>();
        map.put("billType", billType);
        map.put("billNo", billNo);
        map.put("billName",billName) ;
        map.put("signResult",SignResult);
        map.put("yijian",yijian);
        map.put("shenpiBy", shenpiBy);
        map.put("shenpiTime",shenpiTimeStr);
        TemplateMessageDTO messageDTO = new TemplateMessageDTO();
        messageDTO.setTemplateCode("oa_bill_shenqin_receive");
        messageDTO.setFromUser( shenpiBy );
        messageDTO.setToUser(shenqinBy);
        messageDTO.setTemplateParam(map);
        sysBaseAPI.sendTemplateAnnouncement(messageDTO);


        //11. 更新要审批的表
        ShenPiData shenPiData = new ShenPiData();
        shenPiData.setTableName(tableName);
        shenPiData.setTableRecordId(tableRecordId);
        shenPiData.setResultColName(resultColName);
        shenPiData.setYijianColName(yijianColName);
        shenPiData.setShenpiTimeColName(timeColName);
        shenPiData.setShenpiLogColName(shenpiLogColName);
        shenPiData.setSignResult(SignResult);
        shenPiData.setYijian(yijian);
        shenPiData.setShenpiTime(shenpiTime);
        shenPiData.setShenpiLog(shenpiLog);
        baseMapper.shenpi(shenPiData);

        //12. 添加到审批历史记录表
        ComApprovalListLog log =new ComApprovalListLog();
        BeanUtils.copyProperties(comApprovalList,log);
        log.setShenpiBy(username);
        log.setSignResult(SignResult);
        log.setSignYijian(yijian);
        comApprovalListLogService.save(log);

        //13. 删除当前审批记录
        baseMapper.deleteById(comApprovalList.getId());

        Integer jiedianOrdinal = baseMapper.getJiedianOrdinal(tableName, tableRecordId);

        //14. 通过审批结果判断是否需要继续审批
        //通过，进入下一节点
        if( SignResult.equals("通过")){

          //  int count = baseMapper.getDaiShenPiCount(tableName, resultColName, mainRecordId, jiedianOrdinal,resultColName);
            List<Map<String,Object>> shenpiList= baseMapper.getShenPiList(tableName, mainIdColName, mainRecordId, jiedianOrdinal,resultColName);

            //没有找到当前节点未审批的记录，则表示该节点全部审批完成，进入下一节点
            if(shenpiList.isEmpty()){

                //审批完成，更新主表状态为审批通过
                if( resultColName.endsWith("2")){
                    baseMapper.updateMainTableStatus(mainTableName, mainRecordId, "5", username, shenpiTime);//5表示二次审批通过

                }
                else{
                    baseMapper.updateMainTableStatus(mainTableName, mainRecordId, "3", username, shenpiTime);//3表示首次审批通过
                }

            }
            //审批未完成，更新下一节点状态为待审批
            else {
                Map<String, Object> objectMap = shenpiList.get(0);
                Integer finalOrdinal = (Integer) objectMap.getOrDefault("jiedian_ordinal", -1);

                //如果相等，则 表示当前节点未全部审批完成
                if( finalOrdinal.equals(jiedianOrdinal)){
                    return;
                }

                for(Map<String ,Object> Sp: shenpiList){
                    Integer jiedianOrdinal2 = (Integer) Sp.getOrDefault("jiedian_ordinal", 0);

                    if( jiedianOrdinal2.equals(finalOrdinal) ) {

                        String tableRecordId2 = (String) Sp.getOrDefault("id", "");
                        String resultValue = "待审批";

                        //更新审批表状态 待审批
                        baseMapper.updateTableStatus(tableName, tableRecordId2, resultColName, yijianColName, timeColName, resultValue);

                        //添加审批记录
                        addApproval(Sp, comApprovalList, finalOrdinal,false);

                        String jiedianLeader = Sp.getOrDefault("jiedian_leader", "").toString();

                        Map<String, String> map2 = new HashMap<>();
                        map2.put("billType", billType);
                        map2.put("billNo", billNo);
                        map2.put("billName",billName) ;
                        map2.put("shenQinRen", shenqinBy);
                        map2.put("shenQinTime",  shenqinTimeStr);
                        map2.put("remark", comApprovalList.getRemark());

                        //给审批人发送审批消息
                        messageDTO.setFromUser( shenqinBy );
                        messageDTO.setToUser(jiedianLeader);
                        messageDTO.setTemplateCode("oa_bill_shenpi");
                        messageDTO.setTemplateParam(map2);
                        sysBaseAPI.sendTemplateAnnouncement(messageDTO);

                    }
                    else{
                        break;
                    }

                }

                //更新主表审批节点值 finalOrdinal
                baseMapper.updateMainTableOrdinal(mainTableName, mainRecordId, finalOrdinal, username, shenpiTime);

            }

        }
        //驳回，更新主表状态为驳回
        else {
           Integer jiedianOrdinal2 = 0;
            // 设置主表审批节点为子表第一个节点
            List<Map<String,Object>> shenpiList= baseMapper.getShenPiList(tableName, mainIdColName, mainRecordId, jiedianOrdinal2,resultColName);
            Map<String, Object> objectMap = shenpiList.get(0);
            Integer finalOrdinal = (Integer) objectMap.getOrDefault("jiedian_ordinal", -1);

            String billStatus = "0"; //驳回
            if( resultColName.endsWith("2")){
                billStatus ="3";
            }

            // 3表示首次审批通过
            baseMapper.updateMainTableOrdinalStautus(mainTableName, mainRecordId, finalOrdinal, billStatus, username, shenpiTime);

            //更新子表状态为空
            for(Map<String ,Object> Shenpi : shenpiList){
                String id =Shenpi.getOrDefault("id", "").toString();
                String resultValue = "";
                //更新审批表状态 待审批
                baseMapper.updateTableStatus(tableName, id, resultColName, yijianColName, timeColName, resultValue);
            }

        }

    }

    @Override
    public List<ComApprovalList> getByIds(List<String> ids) {
        return baseMapper.selectBatchIds(ids);
    }


    void addApproval(Map<String,Object> Sp, ComApprovalList oaHetong,Integer jiedianOrdinal ,Boolean isLog){
       String billNo = oaHetong.getBillNo();
       String billName = oaHetong.getBillName();
       String billType = oaHetong.getBillType();
       String detailUrl = oaHetong.getDetailUrl();
       String jiedianName = oaHetong.getJiedianName();
       String tableName = oaHetong.getTableName();
       String id = Sp.getOrDefault("id", "").toString();
       String resultColName = oaHetong.getResultColName();
       String yijianColName = oaHetong.getYijianColName();
       String timeColName = oaHetong.getTimeColName();
       String logColName = oaHetong.getLogColName();
       String mainIdColName = oaHetong.getMainIdColName();
       String jiedianLeader = Sp.getOrDefault("jiedian_leader", "").toString();

       if( isLog.equals(false)){
           ComApprovalList comApprovalList = new ComApprovalList();
           comApprovalList.setBillName(billName);
           comApprovalList.setBillType(billType);
           comApprovalList.setBillNo(billNo) ;
           comApprovalList.setDetailUrl(detailUrl);
           comApprovalList.setJiedianName(jiedianName);
           comApprovalList.setJiedianOrdinal(jiedianOrdinal);
           comApprovalList.setTableName(tableName);
           comApprovalList.setTableRecordId(id);
           comApprovalList.setResultColName(resultColName);
           comApprovalList.setYijianColName(yijianColName);
           comApprovalList.setTimeColName(timeColName);
           comApprovalList.setLogColName(logColName);
           comApprovalList.setMainIdColName(mainIdColName);
           comApprovalList.setShenpiBy(jiedianLeader);
           comApprovalList.setSignResult("");
           comApprovalList.setSignYijian("");

           comApprovalList.setShenqinBy(oaHetong.getShenqinBy()) ;
           comApprovalList.setShenqinTime(oaHetong.getShenqinTime()) ;
           comApprovalList.setRemark(oaHetong.getRemark()) ;

           comApprovalListService.save(comApprovalList);
       }
       else {

           ComApprovalListLog comApprovalList = new ComApprovalListLog();
           comApprovalList.setBillName(billName);
           comApprovalList.setBillType(billType) ;
           comApprovalList.setBillNo(billNo) ;
           comApprovalList.setDetailUrl(detailUrl);
           comApprovalList.setJiedianName(jiedianName);
           comApprovalList.setJiedianOrdinal(jiedianOrdinal);
           comApprovalList.setTableName(tableName);
           comApprovalList.setTableRecordId(id);
           comApprovalList.setResultColName(resultColName);
           comApprovalList.setYijianColName(yijianColName);
           comApprovalList.setTimeColName(timeColName);
           comApprovalList.setLogColName(logColName);
           comApprovalList.setMainIdColName(mainIdColName);
           comApprovalList.setShenpiBy(jiedianLeader);

           comApprovalList.setSignResult("");
           comApprovalList.setSignYijian("");

           comApprovalList.setShenqinBy(oaHetong.getShenqinBy()) ;
           comApprovalList.setShenqinTime(oaHetong.getShenqinTime()) ;
           comApprovalList.setRemark(oaHetong.getRemark()) ;

           comApprovalListLogService.save(comApprovalList);
       }

    }




}
